package com.open.capacity.point.service.impl;

import com.open.capacity.point.dao.PointsRuleDao;
import com.open.capacity.point.dto.PointsRuleDto;
import com.open.capacity.point.service.PointsRuleService;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.model.PointsRule;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.web.CodeEnum;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class PointsRuleServiceImpl extends ServiceImpl<PointsRuleDao, PointsRule> implements PointsRuleService {
    @Override
    public PageResult<PointsRuleDto> findRulesByCondition(Map<String, Object> cond) throws ServiceException {
        try {
            PageHelper.startPage(MapUtils.getInteger(cond, PageUtil.PAGE), MapUtils.getInteger(cond, PageUtil.LIMIT), true);
            List<PointsRuleDto> rules = baseMapper.selectRulesCondition(cond);
            PageInfo<PointsRuleDto> pageInfo = new PageInfo<>(rules);
            return PageResult.<PointsRuleDto>builder().code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).data(pageInfo.getList()).build();
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public PointsRule findRuleByCode(String pointsRuleCode) {
        return new LambdaQueryChainWrapper<>(baseMapper).eq(PointsRule::getPointCode, pointsRuleCode).one();
    }

    @Override
    public Result saveOrUpdated(PointsRule pointsRule) throws ServiceException {
        try {
            if (pointsRule.getId() == null) {
                PointsRule queryRule = findRuleByCode(pointsRule.getPointCode());
                if (queryRule != null) return Result.failed("积分规则code已存在");
            }
            boolean flg = saveOrUpdate(pointsRule);
            if (flg) return Result.succeed("操作成功");
        } catch (Exception e) {
            throw new ServiceException(e);
        }
        return Result.failed("出现了一些问题");
    }

    @Override
    public Result delete(String id) throws ServiceException {
        try {
            int flag = baseMapper.deleteById(id);
            return flag > 0 ? Result.succeed("删除成功") : Result.failed("删除失败");
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }
}
